/**
 * ajax获取数据
 * @param  {Object} data 往后端发送的数据对象
 * @return {Promise}      Promise
 */
//$.ajaxSettings({timeout: 15000, accepts: 'application/jso'});
function promiseJsonAjax(url, type, data) {
    var defer = $.Deferred();

    // 这里可以合并一些默认的公用参数，可以使用data来进行覆盖
    data = $.extend({
        // 默认参数
    }, data || {});
    $.showLoading();
    var settings = {
        url: url,
        type: type,
        dataType: 'json',
        timeout: 15000,
    };
    if (type == 'GET') {
        settings['data'] = data;
    }
    if (type == 'POST' || type == 'PATCH' || type == 'PUT') {
        settings['contentType'] = 'application/json';
        settings['data'] = JSON.stringify(data);
    }
    $.ajax($.extend(settings, {
        success: function (res) {
            if (res) {
                defer.resolve(res);
            }
            else {
                // 报错给promise
                defer.reject();
            }
            //会影响成功或者失败后的提示遮罩
            //$.hideLoading();
        },
        error: function () {
            $.hideLoading();
            $.toptips('网络有问题,稍后再试');
            defer.reject();
        }
    }));

    return defer.promise();
};

function promiseJsonGet(url, data) {
    return promiseJsonAjax(url, "GET", data);
}
function promiseJsonPost(url, data) {
    return promiseJsonAjax(url, "POST", data);
}
function promiseJsonUpdate(url, data) {
    return promiseJsonAjax(url, "PATCH", data);
}
function promiseJsonDelete(url, data) {
    return promiseJsonAjax(url, "DELETE", data);
}

var skip_url = from === 'sale' && '/wx/stock/picking_view/' || '/wx/stock/picking_print/';
/**************************************************************************************************
 *
 *  可展开列表
 *
 **************************************************************************************************/
var expandableCategory = Vue.extend({
    props: ['title', 'remote-data'],
    template: '#expandable-category-template',
    data: function () {
        var picking_list = [];
        if (window.picking_list) picking_list = window.picking_list;
        return {
            picking_list: picking_list
        };
    },
    ready: function () {
        console.log('ready')
    },
    methods: {
        expand_or_collapse: function (event) {
            var self = this;
            var $parent = $(event.target).parents('li');
            var $category_item = $(event.target).parent();
            if ($parent.hasClass('js-show')) {
                $parent.removeClass('js-show');
                $category_item.children('i').removeClass('icon-35').addClass('icon-74');
            } else {
                promiseJsonGet(this.remoteData).then(function (data) {
                    $.hideLoading();
                    self.picking_list = data;
                    $parent.siblings().removeClass('js-show');
                    $parent.addClass('js-show');
                    $category_item.children('i').removeClass('icon-74').addClass('icon-35');
                    $parent.siblings().find('i').removeClass('icon-35').addClass('icon-74');
                })
            }
        },
    }
});

// 发送完成提示
var smsSending = Vue.extend({
    created: function () {
        this.count_down();
    },
    data: function () {
        // 如果有剩余倒计时
        if (count_down_seconds > 0) {
            count = count_down_seconds;
        }
        else {
            count = 61;
        }
        return {
            count: count
        }
    },
    template: '<span class="weui-vcode-btn">({{count}})</span>',
    methods: {
        count_down: function () {
            this.count--;
            if (this.count > 0)
                setTimeout(this.count_down, 1000);
            else {
                count_down_seconds = 0;
                this.$parent.sms_button = 'sms-button';
            }
        }
    }
});

// 2.注册组件，并指定组件的标签，组件的HTML标签为<my-component>
Vue.component('expandable-category', expandableCategory);
Vue.component('sms-sending', smsSending);


if (typeof so_id != 'undefined') {
    // 理货单页面
    new Vue({
        el: '#form-tally',
        data: {
            so_id: so_id,
            lines_remainder: lines_remainder
        },
        computed: {
            // 一个计算属性的 getter
            lines_stock_enough: function () {
                var lines_stock_enough = {};
                for (var id in this.lines_remainder) {
                    lines_stock_enough[id] = this.lines_remainder[id].remainder_delivery_qty <= this.lines_remainder[id].available_without_reservation;
                }
                return lines_stock_enough;
            },
            is_whole_picking: function () {
                var is_whole_picking = true;
                for (var id in this.lines_remainder) {
                    var remainder_delivery_qty = this.lines_remainder[id].remainder_delivery_qty;
                    if (remainder_delivery_qty > 0 || remainder_delivery_qty == ''){
                        is_whole_picking = false;
                    }
                }
                return is_whole_picking;
            }
        },
        watch: {
            lines_remainder: {
                handler: function (val, oldVal) {
                    //console.log(oldVal + ' change to:' + val)
                },
                deep: true
            },
        },
        methods: {
            //检查是否已全部建立出库单
            get_is_all_create_picking: function () {

            },
            skip_url: function () {
                 return from === 'sale' && '/wx/stock/picking_view/' || '/wx/stock/picking_print/';
            },
            //检查库存是否足够
            get_stock_enouth: function () {
                var is_stock_enough = true;
                for (var id in this.lines_stock_enough) {
                    if (!this.lines_stock_enough[id]) {
                        is_stock_enough = false;
                        break;
                    }
                }
                return is_stock_enough;
            },

            //建立出库单
            create_stock_picking: function () {
                var self = this;
                console.log(self.skip_url())
                promiseJsonPost('/wx/stock/picking',
                    {so_id: this.so_id, lines_remainder: this.lines_remainder}).then(function (data) {
                    $.hideLoading();
                    var result = data.result;
                    console.log(data);
                    if (result && result.success == true) {
                        $.toast("建立成功!");
                        var picking_id = result.picking_id;
                         console.log(self.skip_url)
                         console.log(picking_id)
                        window.location.href = self.skip_url() + picking_id +"?from="+from;
                    }else {
                        var message = result.error;
                        if (message instanceof Array)
                            message = message.join(', ');
                        $.toptips(message);
                    }
                });
            },

            submit: function () {
                var self = this;
                var $form = $(this.$el);
                //表单校验
                $form.form();
                $form.validate(function (error) {
                    if (error) {
                        //return true; // 如果return true的话，则不会显示错误提示
                    } else {
                        var has_nonzero = false;
                        //检查是否有出库的产品
                        if (self.is_whole_picking) {
                            $.toast("出库数量都为0", "forbidden");
                            return;
                        }
                        promiseJsonGet('/wx/api/stock/available/sale_order/' + self.so_id).then(function (data) {
                                $.hideLoading();
                                //更新最新库存数
                                for (var id in self.lines_remainder) {
                                    self.lines_remainder[id].available_without_reservation = data[id];
                                }
                                //如果库存不足,提示是否强制生成出库单
                                var is_stock_enough = self.get_stock_enouth();
                                if (!is_stock_enough) {
                                    $.toast("库存不足", "forbidden");
                                    //                            $.confirm("强制建立出库单吗?需要等库存足够后再次操作出库单移动出库.", "库存不足, 确认建立?", function() {
                                    //                                self.create_stock_picking();
                                    //                            }, function() {
                                    //                                //取消建立出库单
                                    //                            });
                                }
                                else {
                                    self.create_stock_picking();
                                }
                            },
                            //取得库存error
                            function (error) {
                                if (error)
                                    $.toptips('有错误: ' + error);
                            });
                    }
                });
            }
        }
    });
}


window.update_delivery_user_id = function (data) {
    return promiseJsonUpdate('/wx/api/stock/picking/' + window.picking_id, data);
};

if (typeof window.picking_id != 'undefined') {
    if (typeof window.user_list != 'undefined' && false) {
        //送货人员选择
        $(function () {
            $("#delivery-person-select").select({
                title: "选择送货人",
                items: window.user_list,
                onChange: function (d) {
//                    var self = this;
//                    var old_value = this.$input.val(); //这个语句取不到原值
//                    //d.values + d.titles
//                    var data = {delivery_user_id: d.values};
//                    if (old_value && old_value != d.values){
//                        $.confirm("送货人确认需要更改吗?", "更改?", function() {
//                            //update_delivery_user_id(data);
//                        }, function() {
//                            self.$input.val(old_value);
//                            return false; //阻止不了, 只好把原值赋值回去
//                        });
//                    }
//                    else{
//                        update_delivery_user_id(data);
//                    }
                }
            });
        });
    }
    // 理货单页面
    new Vue({
        el: '#form-picking',
        data: function(){

            return {
                skip_url: from === 'sale' && '/wx/stock/picking_view/' || '/wx/stock/picking_print/',
                picking_id: picking_id,
                state: state,
                move_lines: move_lines,
                user_id: user_id,
                tracking_number: tracking_number,
                delivery_user_id: delivery_user_id,
                is_sign: is_sign,
                picking_user_name: picking_user_name,
                sign_pictures: [],
                note: note,
                packages_number: packages_number,
                shipping_type_sale: shipping_type_sale,
                total_weight_kilo: total_weight_kilo,
                is_show_note_shipping_type: is_show_note_shipping_type
            }
        },
         created: function () {
          this.sign_pictures= _.map( picture_list_rows.reverse(), function (picture) {
                    return 'data:image/png;base64,' + picture
            })
        },
        computed: {
            // 计算某行是否保留
            lines_stock_reserved: function () {
                var lines_stock_reserved = {};
                for (var id in this.move_lines) {
                    if (this.delivery_user_id || this.state == 'assigned' || this.state == 'done') {
                        lines_stock_reserved[id] = true;
                    }
                    else
                        lines_stock_reserved[id] = this.move_lines[id].product_qty == this.move_lines[id].reserved_availability;
                }
                return lines_stock_reserved;
            },
            // 计算是否全部已保留
            is_whole_reserved: function () {
                var is_whole_reserved = true;
                for (var id in this.move_lines) {
                    if (this.move_lines[id].product_qty > this.move_lines[id].reserved_availability) {
                        is_whole_reserved = false;
                    }
                }
                return is_whole_reserved;
            }
        },
        methods: {
            //出库单保留(锁定)库存
            picking_reserve: function () {
                var self = this;
                promiseJsonUpdate('/wx/api/stock/pickings/' + this.picking_id + '/reserve').then(function (data) {
                    console.log(data);
                    //更新最新picking_move保留数
                    for (var id in self.move_lines) {
                        self.move_lines[id].reserved_availability = data.result[id];
                    }
                    $.hideLoading();
                });
            },
            //领货并出库
            picking_take_up: function () {
                var self = this;
                promiseJsonUpdate('/wx/api/stock/pickings/' + this.picking_id + '/pickup?note='+
                    self.note+"&shipping_type_sale="+self.shipping_type_sale + "&total_weight_kilo="
                    + self.total_weight_kilo + "&packages_number=" + self.packages_number).then(function (data) {
                    $.hideLoading();
                    var result = data.result;
                    if (result) {
                        if (result['result'] == true) {
                            self.delivery_user_id = result['user_id'];
                            $('#picking-pickup').addClass('hide');
                        }
                        else {
                            $.toptips(result['message']);
                        }
                    }
                });
            },
            picking_goods: function () {
                var self = this;
                promiseJsonUpdate('/wx/api/stock/pickings/' + this.picking_id + '/picking').then(function (data) {
                    $.hideLoading();
                    var result = data.result;
                    if (result && result['result'] == true) {
                        self.picking_user_name = result['picking_user_name'];
                        $('#picking-pickup_picking').addClass('hide');
                    }
                });
            },
            //送达并签收
            picking_sign: function () {
                var self = this;
                promiseJsonUpdate('/wx/api/stock/pickings/' + this.picking_id + '/sign').then(function (data) {
                    $.hideLoading();
                    var result = data.result;
                    if (result && result['result'] == true) {
                        self.is_sign = true;
                        $('#picking-sign').addClass('hide');
                    }
                });
            },
             //保存快递单号
            change_tracking_number: function () {
                var self = this;
                promiseJsonUpdate('/wx/api/stock/pickings/' +
                    this.picking_id + '/change_tracking_number?tracking_number='+
                    JSON.stringify(this.tracking_number)).then(function (data) {
                    $.hideLoading();
                    var result = data.result;
                    if (result && result['result'] == true) {
                        $.toast("单号修改成功!");
                    }
                });
            },
            //扫描快递单号
            scan_qrcode: function(){
                var self=this;
                wx.scanQRCode({
                    desc: '扫描快递单号',
                    needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function(res) {
                        if (res.resultStr && res.resultStr.indexOf(',')>=0){
                            self.tracking_number = res.resultStr.split(',')[1] + '\n' + self.tracking_number
                        }else{
                            alert('无效条码!')
                        }
                    },
                    error: function(res) {
                        if (res.errMsg.indexOf('function_not_exist') > 0) {
                            alert('版本过低请升级')
                        }
                    }
                });
            },
			// 拍照留存
            take_a_picture: function () {
                var self = this;
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        wx.uploadImage({
                            localId: localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success: function (res) {
                                var serverId = res.serverId; // 返回图片的服务器端ID
                                promiseJsonUpdate('/wx/stock/upload_pickings_image/' + self.picking_id+'/' + serverId).then(function (data) {
                                    $.hideLoading();
                                    var result =  JSON.parse(data.result);
                                    var url = 'data:image/png;base64,' + result.image_sign;
                                    self.sign_pictures = [url].concat(self.sign_pictures);
                                });
                            }
                        });
                    }
                });
            }
        }
    });
}


function load_lodop(development) {
    var script = document.createElement('script');
    var lodop_host = '192.168.0.10';
    if (development == 'development') {
        lodop_host = '127.0.0.1';
    }
    script.setAttribute('src', 'http://' + lodop_host + '/CLodopfuncs.js');
    // 把script标签加入head，此时调用开始
    document.getElementsByTagName('head')[0].appendChild(script);
    $("#btn-print").css("weui-form-preview-btn weui_btn weui_btn_default");
    $("#btn-print").text("打印");
    $("#btn-print").click(function () {
        print_picking();
    });
}
